package com.oneclick.tools.applock;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.HashSet;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.TextView;

import com.oneclick.tools.applock.bean.PackageInfo;
import com.oneclick.tools.applock.db.PackageContentProvider;
import com.oneclick.tools.applock.pattern.ChooseLockPattern;
import com.oneclick.tools.applock.pattern.ConfirmLockPattern;

public class AppLockFragment extends Fragment {
	
	private List<PackageInfo> packageInfos;
	
	private GridView lockedApp;
	private GridView appList;
	
	private Handler callbackHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			
			packageInfos = (List<PackageInfo>) msg.obj;
			AppListAdapter adapter = new AppListAdapter(packageInfos);
			appList.setAdapter(adapter);
		}
	};
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		new Thread() {
			@Override
			public void run() {
				FragmentActivity activity = getActivity();
				
				PackageManager packageManager = activity.getPackageManager();
				
				AppListAdapter adapter = (AppListAdapter) lockedApp.getAdapter();
				ArrayList<PackageInfo> lockedPackage = (ArrayList<PackageInfo>) adapter.packageInfos;
				
				Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
		        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

		        List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
		        HashSet<PackageInfo> hPackages = new HashSet<PackageInfo>();
		        ArrayList<PackageInfo> aPackages = new ArrayList<PackageInfo>();
		        for (ResolveInfo resolveInfo : apps) {
		        	
		        	
		        	String label = resolveInfo.loadLabel(packageManager).toString();
		        	String packageName = resolveInfo.activityInfo.packageName;
		        	PackageInfo packageInfo = new PackageInfo(label, packageName);
		        	
		        	if(!lockedPackage.contains(packageInfo)) {
		        		hPackages.add(packageInfo);
		        	}
				}
		        
		        aPackages.addAll(hPackages);
		        Collections.sort(aPackages, new Comparator<PackageInfo>() {
					@Override
					public int compare(PackageInfo lhs, PackageInfo rhs) {
						return lhs.getLabel().charAt(0) - rhs.getLabel().charAt(0);
					}
				});
		        
		        Message message = callbackHandler.obtainMessage();
		        message.obj = aPackages;
				message.sendToTarget();
			}
		}.start();
	}
	

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		
		ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.layout_lock, null);
		lockedApp = (GridView) viewGroup.findViewById(R.id.lockedApp);
		lockedApp.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int position,
					long when) {
				
				PackageInfo packageInfo = (PackageInfo) adapterView.getItemAtPosition(position);
				new PackageContentProvider(getActivity()).delete(packageInfo.getId());
				packageInfo.setId(0);
				
				int[] fLocation = new int[2];
				view.getLocationOnScreen(fLocation);
				
				TranslateAnimation translateAnimation = new TranslateAnimation(
						TranslateAnimation.ABSOLUTE, 0,
						TranslateAnimation.ABSOLUTE, 0 - fLocation[0],
						TranslateAnimation.ABSOLUTE, 0,
						TranslateAnimation.ABSOLUTE, 0);
				
				translateAnimation.setDuration(800);
				
				AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 0.0f);
				alphaAnimation.setDuration(800);
				
				AnimationSet animationSet = new AnimationSet(true);
				animationSet.addAnimation(translateAnimation);
				animationSet.addAnimation(alphaAnimation);
				animationSet.setDuration(800);
				
				animationSet.setAnimationListener(new AnimationListener2(position));
				view.startAnimation(animationSet);
			}
		});
		
		ArrayList<PackageInfo> packages = new PackageContentProvider(getActivity()).queryPackages();
		
		AppListAdapter adapter = new AppListAdapter(packages);
		lockedApp.setAdapter(adapter);
		
		CheckBox expandBtn = (CheckBox) viewGroup.findViewById(R.id.expandBtn);
		expandBtn.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
				if(checked) {
					lockedApp.setVisibility(View.VISIBLE);
				} else {
					lockedApp.setVisibility(View.GONE);
				}
			}
		});
		
		appList = (GridView) viewGroup.findViewById(R.id.appList);
		appList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int position,
					long when) {
				
				PackageInfo packageInfo = (PackageInfo) adapterView.getItemAtPosition(position);
				long id = new PackageContentProvider(getActivity()).save(packageInfo);
				packageInfo.setId(id);
				
				int[] fLocation = new int[2];
				view.getLocationOnScreen(fLocation);
				
				Animation scaleAnimation = new ScaleAnimation(1.0f, 0.0f, 1.0f,
						0.0f, ScaleAnimation.RELATIVE_TO_SELF, 0.5f,
						ScaleAnimation.RELATIVE_TO_SELF, 0.5f);
				scaleAnimation.setDuration(800);
				
				AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 0.0f);
				alphaAnimation.setDuration(800);
				
				AnimationSet animationSet = new AnimationSet(true);
				animationSet.addAnimation(scaleAnimation);
				animationSet.addAnimation(alphaAnimation);
				animationSet.setDuration(800);
				
				animationSet.setAnimationListener(new AnimationListener1(position));
				view.startAnimation(animationSet);
			}
		});
		
		return viewGroup;
	}
	
	private class AppListAdapter extends BaseAdapter {
		
		private List<PackageInfo> packageInfos;
		private LayoutInflater inflater;
		private PackageManager packageManager;
		
		public AppListAdapter(List<PackageInfo> packageInfos) {
			this.packageInfos = packageInfos;
			inflater = getActivity().getLayoutInflater();
			packageManager = getActivity().getPackageManager();
		}
		
		@Override
		public int getCount() {
			return packageInfos.size();
		}

		@Override
		public Object getItem(int position) {
			return packageInfos.get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			
			PackageInfo packageInfo = packageInfos.get(position);
			ImageView iconView = null;
			TextView nameView = null;
			
			if(convertView == null) {
				convertView = inflater.inflate(R.layout.item_app, null);
			}
			
			iconView = (ImageView) convertView.findViewById(R.id.icon);
			nameView = (TextView) convertView.findViewById(R.id.name);
			if(packageInfo.getId() > 0) {
				convertView.findViewById(R.id.covering).setVisibility(View.VISIBLE);
			} else {
				convertView.findViewById(R.id.covering).setVisibility(View.INVISIBLE);
			}
			
			try {
				iconView.setImageDrawable(packageManager.getApplicationIcon(packageInfo.getPackageName()));
			} catch (NameNotFoundException e) {
				e.printStackTrace();
			}
			nameView.setText(packageInfo.getLabel());
			
			return convertView;
		}
		
	}
	
	private class AnimationListener1 implements AnimationListener {
		
		public int position;
		public AnimationListener1(int position) {
			this.position = position;
		}
		
		
		@Override
		public void onAnimationStart(Animation animation) {}
		
		@Override
		public void onAnimationRepeat(Animation animation) {}
		
		@Override
		public void onAnimationEnd(Animation animation) {
			AppListAdapter adapter = (AppListAdapter) appList.getAdapter();
			List<PackageInfo> packageInfos = adapter.packageInfos;
			PackageInfo packageInfo = packageInfos.get(position);
			packageInfos.remove(position);
			
			adapter.notifyDataSetChanged();
			
			adapter = (AppListAdapter) lockedApp.getAdapter();
			adapter.packageInfos.add(packageInfo);
			adapter.notifyDataSetChanged();
		}
	}
	
	private class AnimationListener2 implements AnimationListener {
		
		public int position;
		public AnimationListener2(int position) {
			this.position = position;
		}
		
		
		@Override
		public void onAnimationStart(Animation animation) {}
		
		@Override
		public void onAnimationRepeat(Animation animation) {}
		
		@Override
		public void onAnimationEnd(Animation animation) {
			AppListAdapter adapter = (AppListAdapter) lockedApp.getAdapter();
			List<PackageInfo> packageInfos = adapter.packageInfos;
			PackageInfo packageInfo = packageInfos.get(position);
			packageInfos.remove(position);
			
			adapter.notifyDataSetChanged();
			
			adapter = (AppListAdapter) appList.getAdapter();
			adapter.packageInfos.add(packageInfo);
			adapter.notifyDataSetChanged();
		}
	}
}
